package pro.lingwu.station.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author @lingwu
 * @date created in 11/18/2021
 */
@Slf4j
@Component
public class FileUtils {

    @Value("${pro.lingwu.station.avatar-base}")
    private String baseURI;

    public String storeFile(String account, MultipartFile file) throws IOException {
        String base = baseURI+"/"+account+"/avatar";
        // 创建目录
        if (!Files.exists(Paths.get(base))){
            try {
                Files.createDirectories(Paths.get(base));
            }catch (IOException exception){
                log.error("Error with make avatar dir");
                throw exception;
            }
        }

        // 删除原先的头像
        Files.newDirectoryStream(Paths.get(base)).forEach(path -> {
            if (Files.isRegularFile(path)) {
                try {
                    Files.delete(path);
                } catch (IOException e) {
                    log.error("Error with remove origin avatar");
                }
            }
        });

        // 储存头像
        String filename = "default_avatar.png";
        if (file == null){
            ClassPathResource resource = new ClassPathResource("static/default_avatar.png");
            resource.getInputStream().transferTo(new FileOutputStream(base+"/"+filename));
        }else {
            filename = file.getOriginalFilename();
            file.transferTo(Paths.get(base+"/"+filename));
        }
        return filename;
    }

}
